function previewImage(input) {
    const preview = document.getElementById('preview');
    const file = input.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function (e) {
            preview.src = e.target.result;
            preview.style.display = 'block';
            input.parentNode.querySelector('.plus-icon').style.display = 'none';
        };
        reader.readAsDataURL(file);
    }
}
function previewImageBlog(input) {
    const preview = document.getElementById('previewBlog');
    const file = input.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function (e) {
            preview.src = e.target.result;
            preview.style.display = 'block';
            input.parentNode.querySelector('.plus-icon').style.display = 'none';
        };
        reader.readAsDataURL(file);
    }
}

function submitTopic() {
    const submitButton = document.getElementById("submittop");
    const id = submitButton.getAttribute("data-topic-id");
    const url = id ? `/end/editTopic/${id}` : document.getElementById("addTopicUrl").value;

    const name = document.getElementById('topicname').value.trim();
    const desc = document.getElementById('topiccontent').value.trim();
    const file = document.getElementById('coverUpload').files[0];

    if (!name) {
        alert('名称不能为空！');
        return;
    }

    const formData = new FormData();
    formData.append('name', name);
    formData.append('desc', desc);

    if (!id || file) {
        formData.append('cover', file);
    }

    fetch(url, {
        method: 'POST',
        body: formData,
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应失败');
        }
        return response.json();  // 👈 期待后端返回 JSON 格式
    })
    .then(result => {
        if (result.code === 0) {
            alert(result.message || '操作成功');
            $('#myModal').modal('hide');

            // 清空表单
            document.getElementById('addTopicForm').reset();
            document.getElementById('preview').src = '';
            document.getElementById('preview').style.display = 'none';
            document.querySelector('.plus-icon').style.display = 'block';

            // 移除编辑标志
            submitButton.removeAttribute("data-topic-id");

            location.reload();
        } else {
            alert('操作失败：' + (result.message || '未知错误'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('提交失败，请稍后重试');
    });
}

function editTopic(id, name, desc, coverUrl) {

    document.getElementById("myModalLabel").innerText = "编辑专题";
    document.getElementById("topicname").value = name;
    document.getElementById("topiccontent").value = desc;

    const preview = document.getElementById("preview");
    preview.src = coverUrl;
    preview.style.display = 'block';
    // console.log(id, name, desc, cover);
    document.querySelector('.plus-icon').style.display = 'none';
    document.getElementById("submittop").setAttribute("data-topic-id", id);

    $('#myModal').modal('show');
}

function deleteTopic(id){
    alert('暂不支持删除分类！！！')
}

function submitblog(topic_id) {
    const submitButton = document.getElementById("submitbg");
    const url = document.getElementById("addBlogUrl").value;

    const title = document.getElementById('blogtitle').value.trim();  // 博客标题
    const fileInput = document.getElementById('blogCoverUpload');
    const file = fileInput.files[0];

    if (!title) {
        alert("请输入文章标题");
        return;
    }

    if (!file) {
        alert("请上传封面图片");
        return;
    }

    // ✅ 预览图片（调用现有 previewImage 方法）
    previewImage(fileInput);

    const formData = new FormData();
    formData.append('title', title);
    formData.append('cover', file);

    // ✅ 获取绑定的专题 ID
    const topicId = submitButton.getAttribute("data-topic-id");
    formData.append('topic_id', topicId);

    submitButton.disabled = true;
    submitButton.innerText = "提交中...";

    fetch(url, {
        method: 'POST',
        body: formData
    }).then(response => {
        if (!response.ok) {
            throw new Error("提交失败");
        }
        return response.json();
    }).then(data => {
        alert("文章新增成功！");
        $('#myModal2').modal('hide');
        location.reload();
    }).catch(error => {
        alert("提交失败：" + error.message);
    }).finally(() => {
        submitButton.disabled = false;
        submitButton.innerText = "提交更改";
    });
}
